I want to be able to use the touch command with the pipeline to create multiple files depending on the output of a command.
Like for example:
grep "hello(.*)" file.txt | touch
But it doesn't work! How can I achieve this?
The touch command itself cannot read from stdin, but you can do it with the help of xargs:
grep "hello(.*)" file.txt | xargs -I file_name touch file_name
Edit:
It the input for xargs contains a line ending with a backslash (\), a file with a newline in its name would be created. The question does not specify what would be the ecpected result in this case.
Example: The input
foo\
bar
would result in a single file named foo\nbar. Adding option -d '\n' to the xargs command would change the behavior to creating two files foo\ and bar.
Try this,
# ~ grep "hello(.*)" file.txt | xargs touch
For more refer : man xargs
xargs touch will tread newlines as well as spaces as markers for individual files. Example: echo -e "hello world\nOne more line" | xargs touch will touch/create five files: hello, world, One, more, and line.
– Abdull
Aug 25 '23 at 11:19
-d '\n'to avoid crating a single filea file\notherfileon lines likea file\newlineotherfile. – αғsнιη May 10 '19 at 09:41echo -e "hello world\nOne more line" | xargs -I file_name touch file_namewill touch/create two files:hello worldandOne more line– Abdull Aug 25 '23 at 11:14