简体   繁体   中英

Shell scripting to print list of elements

Is there any command in shell scripting which is similar to "list" in tcl? I want to write a list of elements to a file (each in separate line) .But, if the element matches a particular pattern then element next to it and the element itself should be printed in the same line. Is there any command in shell script for doing this?

example: my string is like " execute the command run abcd.v" I want to write each word in separate lines of a file but if the word is "run" then abcd.v and run must be printed in the same line. So, the output should be like,

execute
the
command
run abcd.v

How to do this in shell scripting?

line="execute the command run abcd.v"
for word in $line    # the variable needs to be unquoted to get "word splitting"
do
    case $word in
        run|open|etc) sep=" " ;;  
        *) sep=$'\n' ;;
    esac
    printf "%s%s" $word "$sep"
done

See http://www.gnu.org/software/bash/manual/bashref.html#Word-Splitting

Here's how you can do it in bash:

  • Name this following script as list
  • Set it to executable
  • Copy it to your ~/bin/ :

List:

#!/bin/bash
# list

while [[ -n "$1" ]]
do
   if [[ "$1" == "run" ]]; then
       echo "$1 $2"
   else
       echo "$1"
   fi
   shift
done

And this is how you can use it on the command prompt:

list execute the command run abcd.v > outputfile.txt

And your outputfile.txt will be written as:

execute
the
command
run abcd.v

You could accomplish it by using the below script. It would not be a single command. Below is a for loop that has an if statment to check for the keyword run. It does not append a new line character( echo -n ).

for i in `echo "execute the command run abcd.v"`
do 
  if [ $i = "run" ] ; then  
    echo -n "$i " >> fileOutput
  else 
    echo $i >> fileOutput
  fi
done

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