Добавьте строку в файл с awk, вызываемым из bash

Добавьте строку в файл с awk, вызываемым из bash

У меня есть этот файл

127.0.0.1   localhost

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

и я хочу использовать awk для добавления строки после/перед шаблоном 127.0.0.1. Шаблон и строка — это переменные bash.

#!/bin/bash

file="test.txt"
pattern='127.0.0.1'
line='127.0.1.1   cent.centurian.com   centurian'

awk -vpattern="$pattern" -vline="$line" '/pattern/{print;print line;next}1' "$file"

Не работает...

решение1

sedпроще:

sed "/$pattern/a\
$line" "$file"

Выход:

127.0.0.1   localhost
127.0.1.1   cent.centurian.com   centurian

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

ГНУ sedпозволяет использовать однострочную версию вышеизложенного:

sed $file -e "/$pattern/a $line"

...и вывести$line до $pattern, изменитьa(приложение)дляi(вставить):

sed $file -e "/$pattern/i $line"

решение2

Близко. Это ищет (буквальный) шаблон pattern.

Вам необходимо использовать $0 ~ patternдля сопоставления с переменной.

$ pattern='127.0.0.1'
$ line='127.0.1.1   cent.centurian.com   centurian'
$ awk -vpattern="$pattern" -vline="$line" '$0 ~ pattern {print; print line; next} 1' $file | head -2
127.0.0.1   localhost
127.0.1.1   cent.centurian.com   centurian

решение3

Только что создал функцию, которая делает это:

################################################################################
## Adds a line in a file.                                                     ##
#------------------------------------------------------------------------------#
# Given the arguments:                                                         #
# 1st: file                                                                    #
# 2nd: string to find                                                          #
# 3rd: line to add                                                             #
# 4th: 'b' for before, 'a' for after.                                          #
# It adds a line before or after the line containing the search string.        #
################################################################################
function addLineInFileOnString() {
   local file pattern line where tmp
   file="$1"
   pattern="$2"
   line="$3"
   where="$4"
   tmp="$( cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1 )"
   tmp='tmp.'$tmp

   if [[ $where == 'b' ]]; then
      awk -v pattern="$pattern" -v line="$line" '$0 ~ pattern {print line; print; next} 1' "$file" | tee 1>/dev/null $tmp
   elif [[ $where == 'a' ]]; then
      awk -v pattern="$pattern" -v line="$line" '$0 ~ pattern {print; print line; next} 1' "$file" | tee 1>/dev/null $tmp
   fi

   [[ -e $tmp ]] && cp "$tmp" "$file" && rm "$tmp"
}

решение4

Перед совпадающей строкой:

awk -v line='127.0.1.1   cent.centurian.com   centurian' '/127\.0\.0\.1/ \
        { printf "%s\n%s\n", line, $0; next }; 1' file.txt

После совпавшей строки:

awk -v line='127.0.1.1   cent.centurian.com   centurian' '/127\.0\.0\.1/ \
        { printf "%s\n%s\n", $0, line; next }; 1' file.txt

  • /127\.0\.0\.1/соответствует образцу

  • Если шаблон совпадает, желаемый форматированный вывод печатается в printfзависимости от того, будет ли переменная lineнаходиться до или после совпадающей строки.


Пример:

$ cat file.txt                                                                                                              
127.0.0.1   localhost

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

$ awk -v line='127.0.1.1   cent.centurian.com   centurian' '/127\.0\.0\.1/ { printf "%s\n%s\n", $0, line; next }; 1' file.txt
127.0.0.1   localhost
127.0.1.1   cent.centurian.com   centurian

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

$ awk -v line='127.0.1.1   cent.centurian.com   centurian' '/127\.0\.0\.1/ { printf "%s\n%s\n", line, $0; next }; 1' file.txt
127.0.1.1   cent.centurian.com   centurian
127.0.0.1   localhost

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Связанный контент