2

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?

Donal Fellows
  • 120,022
  • 18
  • 134
  • 199
Nathan Pk
  • 639
  • 4
  • 18
  • 25

3 Answers3

1
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

glenn jackman
  • 207,528
  • 33
  • 187
  • 305
0

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
sampson-chen
  • 40,497
  • 12
  • 76
  • 76
0

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
Lipongo
  • 1,177
  • 7
  • 14