我有一个包含记录的文件 (csv);我想浏览每一行,找到不同长度的字母单词并加上引号。
文件内容为:
12345, astringofrandomlength, anotherstringofrandomlength, 2019-01-01
12346, moreastringofrandomlength, otherstringofrandomlength, 2019-01-01
期望的输出是:
12345, 'astringofrandomlength', 'anotherstringofrandomlength', 2019-01-01
12346, 'moreastringofrandomlength', 'otherstringofrandomlength', 2019-01-01
我尝试了以下方法:
sed -e "s/\([A-Za-z]+\)/'\1'/g" datafile.csv
据我所知,我指定了一个组\(\),我在其中搜索任何字母单词[A-Za-z]+,并且我希望在每次出现上述情况时使用反向引用“\1”进行替换每行的单词。但这不起作用,所以我肯定错过了一些东西。
从一个数据文件到另一个数据文件,找到这些单词的字段的位置和数量会有所不同,例如:
12345, astringofrandomlength, 800, anotherstringofrandomlength, stringy, 2019-01-01
12346, moreastringofrandomlength, 980, otherstringofrandomlength, stringzz, 2019-01-01
最佳答案
您的正则表达式是一个 POSIX BRE 模式,它匹配一个字母和一个文字 +
符号,因为 POSIX BRE 模式中的未转义 +
匹配文字加号。
您可以使用以下任一方法解决问题
sed -e "s/\([[:alpha:]]\+\)/'\1'/g" datafile.csv # GNU sed required
sed -E "s/([[:alpha:]]+)/'\1'/g" datafile.csv
sed "s/[[:alpha:]]\{1,\}/'&'/g" datafile.csv
请注意,第一个是 GNU sed 解决方案,第二个使用 POSIX ERE 语法,第二个使用 POSIX BRE \{1,\}
范围量词匹配 1 个或多个重复。请注意,第三个示例中替换模式中的 &
会插入整个匹配项(不需要捕获组)。
关于regex - 使用 sed,在不同长度的单词周围加上引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59057741/