我有一个包含以下内容的文本文件:

Cycle code
Cycle month
Cycle year
Event type ID
Event ID
Network start time

我想更改此文本,以便在有空格时,我想用_替换它。之后,我希望字符小写字母如下:

cycle_code
cycle_month
cycle_year
event_type_id
event_id
network_start_time

我怎么能做到这一点?

有帮助吗?

解决方案

查看sed文档以及注释中的以下建议,以下命令应该有效。

sed -r {filehere} -e 's/[A-Z]/\L&/g;s/ /_/g' -i

其他提示

另一种Perl方法:

perl -pe 'y/A-Z /a-z_/' file

tr单独工作:

tr ' [:upper:]' '_[:lower:]' < file

您的问题中也有perl标记。所以:

#!/usr/bin/perl

use strict; use warnings;

while (<DATA>) {
    print join('_', split ' ', lc), "\n";
}
__DATA__
Cycle code
Cycle month
Cycle year
Event type ID
Event ID
Network start time

或者:

perl -i.bak -wple '$_ = join('_', split ' ', lc)' test.txt
sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ /abcdefghijklmnopqrstuvwxyz_/" filename

如果你有Bash 4,只需使用你的shell

while read -r line
do
    line=${line,,} #change to lowercase
    echo ${line// /_}
done < "file"  > newfile
mv newfile file

使用 gawk

awk '{$0=tolower($0);$1=$1}1' OFS="_" file

使用Perl:

perl -ne 's/ +/_/g;print lc' file

使用Python:

>>> f=open("file")
>>> for line in f:
...   print '_'.join(line.split()).lower()
>>> f.close()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top