0
  1. 我归档 /tmp/txt
  2. 文件内容:aaa aaa aaa _bbb bbb bbb
  3. 我需要保存文件 /tmp/txt_left: aaa aaa aaa
  4. 我需要保存文件 /tmp/txt_right: bbb bbb bbb

!!!注意寻求不使用变量的解决方案!!!

4

4 回答 4

2
awk -F '_'  '{print $1> "/tmp/txt_left"; print $2 > "/tmp/txt_right" }' /tmp/txt
于 2013-03-02T15:18:26.813 回答
1

你可以试着剪断线,在下划线上剪开

Cat /tmp/txt | cut -d_ -f 1 > txt_left
于 2013-03-02T15:17:10.860 回答
1

一种 sed 方式:

更短更快:

sed -ne $'h;s/_.*$//;w /tmp/txt_left\n;g;s/^.*_//;w /tmp/txt_right' /tmp/txt

解释:可以写成:

sed -ne '
    h;        # hold (copy current line in hold space)
    s/_.*$//; # replace from _ to end of line by nothing
    w /tmp/txt_left
              # Write current line to file
              # (filename have to be terminated by a newline)
    g;        # get (copy hold space to current line buffer)
    s/^.*_//; # replace from begin of line to _ by nothing
    w /tmp/txt_right
              # write
 ' /tmp/txt

重击作为

这不是一个真正的变量,我使用第一个参数元素来完成这项工作并在完成后恢复参数列表:

set -- "$(</tmp/txt)" "$@"
echo >>/tmp/txt_right ${1#*_}
echo >>/tmp/txt_left ${1%_*}
shift

我在参数行中将字符串放在第一位,在 , 上进行操作$1,而不是shift参数行,所以没有使用变量,并且很好,参数行返回到他的原始状态

...这是一个纯粹bash的解决方案;-)

于 2013-03-02T16:05:46.807 回答
0

使用 bash 进程替换、tee 和 cut:

tee -a >(cut -d _ -f 0 > /tmp/txt_left) >(cut -d _ -f 1 >/tmp/txt_right) < /tmp/txt
于 2013-03-03T14:58:44.367 回答