4

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?

αғsнιη
  • 41,407
johhnry
  • 43
  • 1
  • 4

2 Answers2

6

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.

Bodo
  • 6,068
  • 17
  • 27
  • you may also need to add -d '\n' to avoid crating a single file a file\notherfile on lines like a file\ newline otherfile. – αғsнιη May 10 '19 at 09:41
  • example: echo -e "hello world\nOne more line" | xargs -I file_name touch file_name will touch/create two files: hello world and One more line – Abdull Aug 25 '23 at 11:14
0

Try this,

# ~ grep "hello(.*)" file.txt | xargs touch

For more refer : man xargs

ss_iwe
  • 1,146
  • 1
    Notice that using 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