通过索引位置获取子字符串

时间:2013-09-01 20:27:10

标签: grep

我需要使用初始和最终位置从一行中提取子字符串。我认为应该很容易用grep完成,但仍然没有想出如何。

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

显然l,k < n和l> ķ

5 个答案:

答案 0 :(得分:5)

Cut是一个不错的选择。您可以选择范围和单个字段:

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

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

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

答案 1 :(得分:4)

为什么不使用awk

echo "12345678" | awk '{print substr($0, 3, 2);}'
# prints '34'

答案 2 :(得分:2)

如果你正在使用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

答案 3 :(得分:0)

使用

k=3
echo '123456789' | sed 's/^.\{'$k'\}//'

输出:

456789

答案 4 :(得分:-1)

这是你想要的吗?

    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);
相关问题