Using output of awk to run command

前端 未结 3 1693
终归单人心
终归单人心 2021-02-05 02:39

I am brand new to shell scripting and cannot seem to figure out this seemingly simple task. I have a text file (ciphers.txt) with about 250 lines, and I would like to use the fi

3条回答
  •  不知归路
    2021-02-05 03:24

    The xargs command is specifically for that use case.

    awk '{print $0}' >results.txt
    

    This version is a bit longer for the example case because awk was already being used to parse out $0. However, xargs comes in handy when you already have a list of things to use and are not running something that can execute a subshell. For example, awk could be used below to execute the mv but xargs is a lot simpler.

    ls -1 *.txt | xargs -I{} mv "{}" "{}.$(date '+%y%m%d')"
    

    The above command renames each text file in the current directory to a date-stamped backup. The equivalent in awk requires making a variable out of the results of the date command, passing that into awk, and then constructing and executing the command.

    The xargs command can also accumulate multiple parameters onto a single line which is helpful if the input has multiple columns, or when a single record is split into recurring groups in the input file.

    For more on all the ways to use it, have a look at "xargs" All-IN-One Tutorial Guide over at UNIX Mantra.

提交回复
热议问题