开发者

Writing to a file through a bash script

开发者 https://www.devze.com 2023-01-19 17:51 出处:网络
I want to write a bash script which takes 2 arguments, a and b. Based on the argument, it writes in secti开发者_运维技巧on a or section b of a text file.

I want to write a bash script which takes 2 arguments, a and b. Based on the argument, it writes in secti开发者_运维技巧on 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.


#!/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


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号