AWK 代码丢弃换行符
AWK code discard the newline character
我正在尝试删除日期函数的换行符并让它包含空格。我正在使用这个保存变量:
current_date=$(date "+%m/%d/%y AT %H:%M:%S" )
我需要日期保留在当前文本行中,除非指定,否则不换行。
current_date=$(date "+%m/%d/%y AT %H:%M:%S" )
awk '(++n==2) {print "1\nData \nAccount '$current_date' Terminated; n=0} (/blah/) {n=0} {print}' input file > output file
输入:
Line 1
Line 2
Line 3
输出:
Line 1
Line 2
Data
Account '$current_date'
Terminated
Line 3
期望的输出:
Line 1
Line 2
Data
Account '$current_date' Terminated
Line 3
我不得不在你的 awk 命令中添加 3 个双引号:
awk '(++n==2) {print "1\nData \nAccount '"$current_date"' Terminated"; n=0} (/blah/) {n=0} {print}' foo.txt
当您关闭单引号并在 $current_date
之前和之后重新打开它时,您需要在变量周围加上双引号,以便它将标记放在空格周围。然后你需要在 Terminated 之后再引用一个引号来完成字符串。
我应该补充一点,在进行这些更改之前我遇到了语法错误,所以可能还有其他问题...
与其尝试使用 shell 语法将 shell 变量放入 awk 代码中,将 shell 变量简单地分配给 awk 通常更简单、更安全带有 -v
选项的变量:
$ awk -v d="$current_date" '{print} (++n==2) {printf "Data \nAccount %s Terminated\n",d; n=0} (/blah/) {n=0}' file
Line 1
Line 2
Data
Account 03/23/15 AT 14:34:10 Terminated
Line 3
从变量中删除多余的换行符 current_date
假设我们向 current_date
添加多余的换行符:
current_date=$(date "+%m/%d/%y AT%n %H:%M:%S%n%n" )
我们可以按如下方式删除它们:
$ awk -v d="$current_date" 'BEGIN{sub(/\n/,"",d)} {print} (++n==2) {printf "Data \nAccount %s Terminated\n",d; n=0} (/blah/) {n=0}' file
Line 1
Line 2
Data
Account 03/23/15 AT 15:41:17 Terminated
Line 3
我正在尝试删除日期函数的换行符并让它包含空格。我正在使用这个保存变量:
current_date=$(date "+%m/%d/%y AT %H:%M:%S" )
我需要日期保留在当前文本行中,除非指定,否则不换行。
current_date=$(date "+%m/%d/%y AT %H:%M:%S" )
awk '(++n==2) {print "1\nData \nAccount '$current_date' Terminated; n=0} (/blah/) {n=0} {print}' input file > output file
输入:
Line 1
Line 2
Line 3
输出:
Line 1
Line 2
Data
Account '$current_date'
Terminated
Line 3
期望的输出:
Line 1
Line 2
Data
Account '$current_date' Terminated
Line 3
我不得不在你的 awk 命令中添加 3 个双引号:
awk '(++n==2) {print "1\nData \nAccount '"$current_date"' Terminated"; n=0} (/blah/) {n=0} {print}' foo.txt
当您关闭单引号并在 $current_date
之前和之后重新打开它时,您需要在变量周围加上双引号,以便它将标记放在空格周围。然后你需要在 Terminated 之后再引用一个引号来完成字符串。
我应该补充一点,在进行这些更改之前我遇到了语法错误,所以可能还有其他问题...
与其尝试使用 shell 语法将 shell 变量放入 awk 代码中,将 shell 变量简单地分配给 awk 通常更简单、更安全带有 -v
选项的变量:
$ awk -v d="$current_date" '{print} (++n==2) {printf "Data \nAccount %s Terminated\n",d; n=0} (/blah/) {n=0}' file
Line 1
Line 2
Data
Account 03/23/15 AT 14:34:10 Terminated
Line 3
从变量中删除多余的换行符 current_date
假设我们向 current_date
添加多余的换行符:
current_date=$(date "+%m/%d/%y AT%n %H:%M:%S%n%n" )
我们可以按如下方式删除它们:
$ awk -v d="$current_date" 'BEGIN{sub(/\n/,"",d)} {print} (++n==2) {printf "Data \nAccount %s Terminated\n",d; n=0} (/blah/) {n=0}' file
Line 1
Line 2
Data
Account 03/23/15 AT 15:41:17 Terminated
Line 3