如何获得排序、定义或除给定列之外或之后或之前的所有列

How to get ordered, defined or all columns except or after or before a given column

在BASH 我 运行 以下一个班轮在拆分给定字符后得到一个单独的 column/field (如果他们想拆分多个字符,也可以使用 AWK,即以任何顺序拆分一个单词,好的)。

#This will give me first column i.e. 'lori' i.e. first column/field/value after splitting the line / string on a character '-' here
echo "lori-chuck-shenzi" | cut -d'-' -f1

# This will give me 'chuck'
echo "lori-chuck-shenzi" | cut -d'-' -f2

# This will give me 'shenzi'
echo "lori-chuck-shenzi" | cut -d'-' -f3

# This will give me 'chuck-shenzi' i.e. all columns after 2nd and onwards.
echo "lori-chuck-shenzi" | cut -d'-' -f2-

注意上面的最后一个命令,我如何在 Groovy 中执行相同的最后一个 cut 命令?

例如:如果内容在文件中并且看起来像:

1 - a
2 - b
3 - c
4 - d
5 - e
6 - lori-chuck shenzi
7 - columnValue1-columnValue2-columnValue3-ColumnValue4

我尝试了以下 Groovy 代码,但它没有给我 lori-chuck shenzi(即在忽略第 6 个项目符号和 - 的第一次出现后,我希望我的输出是lori-chuck shenzi 并且下面的脚本只返回 lori (这给了我正确的输出,因为我的索引在下面的代码中是 [1],所以我知道)。

def file = "/path/to/my/file.txt"

File textfile= new File(file) 

//now read each line from the file (using the file handle we created above)
textfile.eachLine { line -> 
    //list.add(line.split('-')[1])
    println "Bullet entry full value is: " + line.split('-')[1]
}
// return list

此外,上面文件的最后一行是否有简单的方法,如果我可以使用 Groovy 代码在拆分后更改列的顺序,即像我们在Python [1:]、[:1]、[:-1] 等。或以某种方式

如果我没有正确理解你的问题,你想要的是:

line.split('-')[1..-1]

这将为您提供从位置 1 到最后的位置。您可以执行 -2(倒数第二个)等等,但请注意,如果您越过数组的开头,您也可以获得 ArrayIndexOutOfBoundsException 向后移动!

-- 原答案在这一行之上--

添加到我的答案中,因为评论不允许代码格式化。如果你只想选择特定的列,最后想要一个字符串,你可以这样做:

def resultList = line.split('-')
def resultString = "${resultList[1]}-${resultList[2]} ${resultList[3]}"

然后选择您想要的任何列。我以为您正在寻找更通用的解决方案,但如果不是,特定的列很容易!

如果您想要第一个值,破折号,然后由空格连接的其余值,只需使用:

"${resultList[1]}-${resultList[2..-1].join(" ")}"

我不知道如何为您可能想要的每种组合提供具体答案,但基本上一旦您在列表中有了您的值,您就可以随心所欲地操作它,并将结果转回一个字符串使用 GStrings 或使用 .join(...).

我不喜欢这个解决方案,但我这样做是为了让它工作。从 [1..-1 获取索引值后(即从第一个索引,不包括第 0 个索引,即第一次出现 - 字符的左侧),我不得不删除 [] (LIST) 使用 join(',') 然后用 - 替换任何 , 以获得我正在寻找的最终结果。

list.add(line.split('-')[1..-1].join(',').replaceAll(',','-'))

我仍然想知道什么是更好的解决方案,以及当我们谈论以给定顺序挑选单个列 + 时如何工作(而不是我编写各种 Groovy 语句来从中选择单个元素string/list 每条语句)。