简体   繁体   中英

Arguments to a shell script from a text file

I have a text file (Text.txt) having content as follows,

  1. Name1 Text1
  2. Name2
  3. Name3 Text3

I want to write a shell script where i have to take Name1 , Name2 and Name3 as first arguments and Text1/Text3 as second argument . Condition: My script should check each line if second argument is present.

My output should be displayed as follows :

  1. Arg1: Name1 Arg2: Text1
  2. Arg1: Name2 Arg2: No args found
  3. Arg1: Name3 Arg2: Text3

I dont know where to start. Can someone help me on .

Using read in an while loop:

while read -r cmd args; do
  printf "Arg1: %s Arg2: %s\n" "$cmd" "${args:-No args found}"
done < Text.txt

Bash Parameter expansion is used here with ${args:-No args found} that set $args with No args found value is it's unset or null.

I removed the leading numbers as I'm not sure they are present in your text file.

You can run the following :

awk -F' ' '{ 
 printf $1" Arg1: "$2" Arg2: ";
 if(length($3)){
  print $3}
 else {
  print "No args found"}
 }' Text.txt

It prints the first two columns with your desired input, and checks for a third one (with the if ) for the last output.

EDIT : If the line numbers ( 1. , 2. , etc.) aren't part of the text file, update the command line to the following :

 awk -F' ' '{ 
  printf "Arg1: "$1" Arg2: ";
  if(length($2)){
   print $2}
  else {
   print "No args found"}
  }' Text.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM