tags:

views:

21

answers:

2

I want to write a bash script which takes 2 arguments, a and b. Based on the argument, it writes in section a or section b of a text file.

Output file is a txt file something like this:

common content....
section a:
<everything should be written here when I specify option "a">
section b:
<everything should be written here when I specify option "b">

I am new to bash.

A: 

Following script writes the modified content of a file (filename is stored in the file variable) to standard output.

The new section content is taken from standard input.

#!/bin/bash
file=text.txt

# write the file contents up to desired section (or the whole file)
sed -n '1,/^section '"$1"':$/p' "$file"

# write standard input
cat

# write the rest of the file
sed -n '/^section '"$1"':$/,${n;p}' "$file"
hluk
A: 
#!/bin/bash


if [ "$#" -eq 2 ];then
 secA="$1"
 secB="$2"
elif [ "$#" -eq 1 ];then
 secA="$1"
fi

awk -v s1="$secA" -v s2="$secB" '
/section a/ && s1{
  $0=$0"\n"s1
  while(getline line){
   if (line~/section b/) { $0=$0"\n"line;break}
  }
}
/section b/ && s2{ $0=$0"\n"s2}
1' file
ghostdog74