Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.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 在文本文件中添加引号_Bash_Sed - Fatal编程技术网

Bash 在文本文件中添加引号

Bash 在文本文件中添加引号,bash,sed,Bash,Sed,我需要在列表中添加引号。稍后我将把这个列表导入给邮递员 我的清单如下: SurName Name email@host.foo otherSurName otherName otheremail@host.bar awk '{$1="\""$1; $2=$2"\""}1' file 我需要的是: "SurName Name" email@host.foo 我希望使用sed可以做到这一点,但无法想象如何做到。如果您的整个文件都是这样排序的,您只需使用 sed-e的/^\(.*\)\(.*\)

我需要在列表中添加引号。稍后我将把这个列表导入给邮递员

我的清单如下:

SurName Name email@host.foo
otherSurName otherName otheremail@host.bar
awk '{$1="\""$1; $2=$2"\""}1' file
我需要的是:

"SurName Name" email@host.foo

我希望使用sed可以做到这一点,但无法想象如何做到。

如果您的整个文件都是这样排序的,您只需使用
sed-e的/^\(.*\)\(.*\)\(.*\)$/“\1\2”\3/”
尝试执行以下操作:

sed -r 's/^(.*) +(.*@.*)/"\1" \2/' file


此表单允许在名称部分使用
0到N
空格,而
sed
命令将注意到第一个引号很简单,
s/^/“/
,第二个引号有点棘手,但您可以使用以下模式将其锚定到电子邮件地址:
s/*[^@*[^@*$/”&/
,例如:

sed 's/^/"/; s/ *[^@ ]*@[^@]*$/"&/' file
输出:

"SurName Name" email@host.foo
"otherSurName otherName" otheremail@host.bar

另一个sed选项:

sed '{
s/^/"/
s/ \([^ ]*\)$/" \1/
}' inputFile
同一行上的内容:

sed 's/^/"/;s/ \([^ ]*\)$/" \1/' inputFile

使用
awk
您可以这样做:

SurName Name email@host.foo
otherSurName otherName otheremail@host.bar
awk '{$1="\""$1; $2=$2"\""}1' file
试验

如果还希望处理只有两列的情况,请执行以下操作:

$ awk '{if (NF==2) $1="\""$1"\""; else {$1="\""$1; $2=$2"\""}}1' file
"SurName Name" email@host.foo
"otherSurName otherName" otheremail@host.bar
"thirdname" sdfff@sdff.go
awk '{if(NF>2){$1="\""$1; $2=$2"\""}}1' file
或者,如果知道只有2列或3列,您可以将其缩短一点:

awk '{$1="\""$1;$(NF-1)=$(NF-1)"\""}1' file
如果要处理没有名称的行,请执行以下操作:

$ awk '{if (NF==2) $1="\""$1"\""; else {$1="\""$1; $2=$2"\""}}1' file
"SurName Name" email@host.foo
"otherSurName otherName" otheremail@host.bar
"thirdname" sdfff@sdff.go
awk '{if(NF>2){$1="\""$1; $2=$2"\""}}1' file
演示


你的整个文件都是这样排列的吗?是的,只是有些行缺少名字和姓氏…两者都只是列出了一个'email@host.foo“入口的,他们似乎完全切断了名字的…”-(真可耻!在我的第一次测试中,我使用了旧版本的列表,其中只包含邮件addi的…抱歉,使用了正确的“文件”你的第一行工作正常!!!它们都用引号括住了邮件addi,但行中没有包含名称…@Mircsicz我添加了一行,仅当行中有两个以上的单词时才添加引号