cat output of ls, each files

This will cat all files on the current dir

EDIT: This might not be a good idea. A colleague of my warns off. Thanks to him sharing me this link :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:

  1. ls: Lists the files in the current directory.

  2. |: Pipes the output of the ls command to the next command.

  3. 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.

  4. sh -c 'echo "==> {} <=="; cat {}': Executes the echo and cat 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.

  5. |: Pipes the output of the subshell to the awk command.

  6. 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 variable filename to the current line and skip to the next line.

    • {print filename, $0}: For each remaining line, print the filename variable followed by the original line content.