Grep 按索引位置获取子字符串

Grep 按索引位置获取子字符串,grep,sed,Grep,Sed,我需要使用初始和最终位置从一行中提取一个子字符串。我认为用grep应该很容易做到,但还没有弄明白怎么做 例如,一行n个字符,我想提取从k位置开始到l位置结束的子字符串 显然是l,kk为什么不使用 为什么不使用 这就是你要找的吗 String test = "ateststring"; String testa = test.substring(0,4); String test2 = testa.substring(0,3); int testc = test.i

我需要使用初始和最终位置从一行中提取一个子字符串。我认为用grep应该很容易做到,但还没有弄明白怎么做

例如,一行n个字符,我想提取从k位置开始到l位置结束的子字符串

显然是l,kk

为什么不使用

为什么不使用


这就是你要找的吗

    String test = "ateststring";
    String testa = test.substring(0,4);
    String test2 = testa.substring(0,3);
    int testc = test.indexOf("test");
    String test3 = test.substring(testc,5);

    System.out.println(test + ":" + testa + ":" + test2 + ":" +test3);

这就是你要找的吗

    String test = "ateststring";
    String testa = test.substring(0,4);
    String test2 = testa.substring(0,3);
    int testc = test.indexOf("test");
    String test3 = test.substring(testc,5);

    System.out.println(test + ":" + testa + ":" + test2 + ":" +test3);

如果您使用的是bash,您可以执行以下操作:

LINE="strings"
K=3  ## 4th character starting from index 0
L=5  ## 6th character starting from index 0
echo "${LINE:K:L - K + 1}"
在文件的循环中:

while -r read LINE; do echo "${LINE:K - 1:L - K}"; done < file
对于awk,L表示位置,而不是长度,其中0是起始索引:

awk -v k="3" -v l="5" '{ n = length; print substr($0, k, l - k + 1);}' < file

如果您使用的是bash,您可以执行以下操作:

LINE="strings"
K=3  ## 4th character starting from index 0
L=5  ## 6th character starting from index 0
echo "${LINE:K:L - K + 1}"
在文件的循环中:

while -r read LINE; do echo "${LINE:K - 1:L - K}"; done < file
对于awk,L表示位置,而不是长度,其中0是起始索引:

awk -v k="3" -v l="5" '{ n = length; print substr($0, k, l - k + 1);}' < file

切割是一个很好的选择。您可以选择范围和单个字段:

$ echo "123456" | cut -c2-4
234

$ echo "123456" | cut -c1,3,6
136

$ echo "123456" | cut -c1-3,6
1236

切割是一个很好的选择。您可以选择范围和单个字段:

$ echo "123456" | cut -c2-4
234

$ echo "123456" | cut -c1,3,6
136

$ echo "123456" | cut -c1-3,6
1236
使用:

输出:

使用:

输出:


非常感谢兄弟!不客气。awk会将此应用于文件中的每一行。我不知道您想如何管理文件或多行输入。如果你搜索的话,你可以用awk做更多的事情。非常感谢你的兄弟!不客气。awk会将此应用于文件中的每一行。我不知道您想如何管理文件或多行输入。如果你搜索,你可以用awk做更多的事情。