cat output of ls, each files
EDIT: This might not be a good idea. A colleague of my warns off. Thanks to him sharing me this link :http://mywiki.wooledge.org/ParsingLs
If you attempt to parse the output of ls, the script or program you're writing might get confused by filenames with special characters or even whitespace. This could lead to incorrect results, or even worse, unexpected and potentially harmful behaviors if your script uses this parsed output for further operations, such as file deletion or modification.Original article :
Here is a 1-liner that will cat each output of ls. Use it with caution since it may produce unexpected results if the directory contains non-text files or a large number of files.
ls | xargs -I {} sh -c 'echo "==> {} <=="; cat {}' | awk '/==>/{filename=$0;next} {print filename, $0}'
This command breaks down as follows:
ls
: Lists the files in the current directory.
|
: Pipes the output of thels
command to the next command.
xargs -I {}
: Takes the input from the pipe and allows you to use the placeholder{}
to represent each individual input item in the following command.
sh -c 'echo "==> {} <=="; cat {}'
: Executes theecho
andcat
commands in a subshell for each file.
echo "==> {} <==";
: Prints a header with the file name.
cat {}
: Concatenates and prints the contents of each file represented by the{}
placeholder.
|
: Pipes the output of the subshell to theawk
command.
awk '/==>/{filename=$0;next} {print filename, $0}'
: Processes the output to prepend the file name to each line of the file content.
/==>/{filename=$0;next}
: If the line matches the pattern==>
, set the variablefilename
to the current line and skip to the next line.
{print filename, $0}
: For each remaining line, print thefilename
variable followed by the original line content.
Subscribe to my newsletter
Read articles from Daniel Muyshond (Dan) directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Daniel Muyshond (Dan)
Daniel Muyshond (Dan)
Intégrateur d'applications web open source expérimenté avec plus de 5 ans d'expertise le suivi d'intégration d'applications web Python 3 containerisées, assistance technique et résolution de problèmes, suivi et intégration de développements et tests. Initialement axé sur le support client et la résolution de problèmes, j'ai développé des compétences en suivi et réalisation d'intégrations techniques et développements en rapport avec la maintenance, le suivi, la mise à jour de la pile applicative, ou les exigences ou problèmes remontés par le client. Je recherche de nouvelles opportunités pour mettre à profit mes compétences techniques et interpersonnelles dans un environnement stimulant.