Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash AWK代码丢弃换行符_Bash_Shell_Awk_Formatting - Fatal编程技术网

Bash AWK代码丢弃换行符

Bash AWK代码丢弃换行符,bash,shell,awk,formatting,Bash,Shell,Awk,Formatting,我试图删除日期函数的新行字符,并使其包含空格。我使用以下方法保存变量: 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}

我试图删除日期函数的新行字符,并使其包含空格。我使用以下方法保存变量:

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\u date
之前和之后关闭单引号并重新打开它时,需要在变量周围加上双引号,这样它就可以在空格周围将标记放在一起。然后在结束后需要另一个引号来完成字符串


我应该补充一点,在我进行这些更改之前,我遇到了语法错误,因此可能还有其他问题…

与其尝试使用shell语法将shell变量放入awk代码中,不如使用
-v
选项将shell变量简单地分配给awk变量:

$ 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\u 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

当我运行你的代码时,我并没有得到你的输出,而是我一直在接收的输出,它在一个新的位置终止line@Skonectthedots我无法重现这一点,但请参阅更新的答案,了解一种更积极地删除不需要的换行符的方法。如果这不起作用,请用
declare-p current_date
的结果更新您的问题@John1024将需要gsub如果
中暗示有多个换行符,我们将添加多余的换行符
您发布的脚本不可能生成您发布的输出,因为它包含语法错误。修复语法错误,然后运行脚本,然后发布脚本及其输出。目前,我们正试图帮助您调试一个我们还没有看到的脚本,该脚本根据您目前告诉我们的情况,产生不可能的输出-我们极不可能成功。
awk'NR==3{print“data\nacount”strftime(“%m/%d/%y AT%H:%m:%s”)“terminated”}1'
awk
代码中以这种方式使用变量不是一个好主意。请参见以下John1024s答案或我的答案: