mcE*_*nge 1 command-line bash sed text-processing
我有一个命令,它向我输出一个具有以下模式的列表
exp_70_T8_s1
exp_71_T8_s5
exp_72_T8_s10
exp_73_T10_s1
exp_74_T10_s5
exp_75_T10_s10
...
Run Code Online (Sandbox Code Playgroud)
如何分别使用sed
bash中的“_T”和“_s”或类似的东西获取“_T”和“_s”之后的数字?
输出应该是这样的
8
8
8
10
10
10
Run Code Online (Sandbox Code Playgroud)
和
1
5
10
1
5
10
Run Code Online (Sandbox Code Playgroud)
对于_T
和_s
分别
我的命令的第一部分如下所示:
for f in $(find . -name "someFile.txt" | sort); do echo $f; done | grep /someFolderName/
Run Code Online (Sandbox Code Playgroud)
基本上我想将命令添加到上面给出的命令中。
sed
与模式分组一起使用来捕获所需的部分:
your_command | sed -r 's/.*_T([0-9]+)_s([0-9]+)$/\1 \2/'
Run Code Online (Sandbox Code Playgroud)
([0-9]+)
是第一个捕获的组,[0-9]
匹配之间的任何数字0-9
并在这种情况下+
表示前一个标记的一个或多个匹配[0-9]
([0-9]+)
是第二个被捕获的组
在替换模式中,两个捕获的组分别由\1
和引用\2
。
例子:
$ cat file.txt
exp_70_T8_s1
exp_71_T8_s5
exp_72_T8_s10
exp_73_T10_s1
exp_74_T10_s5
exp_75_T10_s10
$ sed -r 's/.*_T([0-9]+)_s([0-9]+)/\1 \2/' file.txt
8 1
8 5
8 10
10 1
10 5
10 10
Run Code Online (Sandbox Code Playgroud)
更改替换模式以满足您的需要,例如没有任何空间:
your_command | sed -r 's/.*_T([0-9]+)_s([0-9]+)/\1\2/' file.txt
Run Code Online (Sandbox Code Playgroud)
回答编辑后的问题:
对于_T
:
your_command | grep -Po '.*_T\K\d+' ## Using grep
your_command | sed -r 's/.*_T([0-9]+).*/\1/' ## Using sed
Run Code Online (Sandbox Code Playgroud)
对于_s
:
your_command | grep -Po '.*_s\K\d+$' ## Using grep
your_command | sed -r 's/.*_s([0-9]+)$/\1/' # Using sed
Run Code Online (Sandbox Code Playgroud)
使用 AWK:
command | awk -F_T\|_s '{print $2}'
Run Code Online (Sandbox Code Playgroud)
command |
awk -F_T\|_s '
{
print $2
}
'
Run Code Online (Sandbox Code Playgroud)
和:
command | awk -F_T\|_s '{print $3}'
Run Code Online (Sandbox Code Playgroud)
command |
awk -F_T\|_s '
{
print $3
}
'
Run Code Online (Sandbox Code Playgroud)
command
输出文件的命令在哪里。
-F_T\|_s
: 设置_T
和_s
作为输入字段分隔符;{print $2}
: 打印第二个字段。{print $N}
: 打印第三个字段。% cat file
exp_70_T8_s1
exp_71_T8_s5
exp_72_T8_s10
exp_73_T10_s1
exp_74_T10_s5
exp_75_T10_s10
% cat file | awk -F_T\|_s '{print $2}'
8
8
8
10
10
10
% cat file | awk -F_T\|_s '{print $3}'
1
5
10
1
5
10
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1133 次 |
最近记录: |