Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print $1, $2 and then all remaining parameters together in AWK

Tags:

shell

sed

awk

I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

sctl   sudo         systemctl
pac    sudo         pacman

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

    sed "s/\s*#.*$//;/^\s*$/d" $command_file | 
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file

And the end result would be something like this:

abbr sctl "sudo systemctl"
abbr pac "sudo pacman"

But this code doesn't work when the line has many parts after the 3rd parameter:

svu    playerctl    -p spotify volume +0.05

How can i go about printing in that format? $1 $2 ($3..$N)

like image 697
Onizudo Avatar asked Sep 16 '25 09:09

Onizudo


1 Answers

You can erase the first two fields and trim the space from the remainder, eg.

{ 
  printf "%s %s ", $1, $2
  $1=$2=""; sub(/^\s*/, "", $0);
  printf "\"%s\"\n", $0
}

With output like,

svu playerctl "-p spotify volume +0.05"

Note: the \s regex requires gnu awk as pointed out by Ed Morton.

like image 198
Rorschach Avatar answered Sep 18 '25 09:09

Rorschach