将 x/ 添加到行,其中 x 是每行上的一个变量

Oxw*_*ivi 1 bash sed

我想$x/从格式化为$x-xyz(xyz是要忽略的文本和数字的混合) 的数据中添加。

示例数据

AB-10C
CD-02E
Run Code Online (Sandbox Code Playgroud)

输出

AB/AB-10C
CD/CD-02E
Run Code Online (Sandbox Code Playgroud)

如何在连字符之前将变量描述为文本?我的想法是:

define $x = # don't know how to do that
## and then somehow use sed to prepend
sed -i s/$/$x/ file
# I don't know if sed can handle variables though - the above one liner is from Googling
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 5

这是一个快速而肮脏的awk版本:

awk -F- '{print $1"/"$0}' input_file > output_file
Run Code Online (Sandbox Code Playgroud)

它的作用是-用作字段分隔符,并打印第一列(即第一列之前的所有内容-),然后是 a /,然后是整个原始行。

做同样事情的一种方法sed是:

sed -e 's;^\([^-]*\)\(.*\);\1/\1\2;' input_file > output_file
Run Code Online (Sandbox Code Playgroud)

(但这几乎不可读。)

如果你想简单地做bash,你可以使用字符串操作:

$ foo=AB-10C
$ prefix=${foo%%-*}
$ echo ${prefix}/${foo}
AB/AB-10C
Run Code Online (Sandbox Code Playgroud)

while read如果数据来自文件,则在循环或类似情况下使用它。