【问题标题】:How to read text from a file line by line, capitalize the first letter of every word, then write to a different file Using Bash?如何逐行读取文件中的文本,将每个单词的第一个字母大写,然后使用 Bash 写入不同的文件?
【发布时间】:2022-10-04 12:23:18
【问题描述】:

我正在寻找带有名称的文件。我试图确保每个名字都正确大写。期望结果的示例

cat names.txt
joHn smiTH
MichAel jAckson
Hello World
annie-marie

运行代码时:

./namefixer.bash names.txt fixedNames.txt

cat fixedNames.txt
John Smith
Michael Jackson
Hello World
Annie-Marie

有什么帮助吗?

我当前的代码如下所示:

#!/bin/bash

while IFS= read -r line
do
     "$line" |tr '[:upper:]' '[:lower:]'
     for word in $line
     do
           mv -- "$word" "${word^}"
     done
     $line>>$2
done < $1

【问题讨论】:

    标签: bash capitalization


    【解决方案1】:

    可以使用rquery(https://github.com/fuyuncat/rquery/releases)提供的camelstr函数

    [ rquery]$ cat samples/names.txt
    joHn smiTH
    MichAel jAckson
    Hello World
    annie-marie
    [ rquery]$ ./rq -q "s camelstr(@raw) | >'samples/fixedNames.txt'" samples/names.txt
    [ rquery]$ cat samples/fixedNames.txt
    John Smith
    Michael Jackson
    Hello World
    Annie-Marie
    

    【讨论】:

    • 您是否与 rquery 有任何关系?
    【解决方案2】:

    你可以用 GNU sed 做到这一点:

    sed -E 's/(w)(w*)/uL/g' names.txt > fixedNames.txt
    

    这会在第一个捕获组中捕获 "word" character (w),然后在第二个捕获组 (w*) 中捕获尽可能多的“单词”字符,并使用 special u and L sequences 来控制替换中的大小写细绳。 g 标志对每一行全局应用更改(而不仅仅是第一个匹配)。

    如果它确实必须适合您显示的确切命令,您可以将这些内容设为namefixer.bash

    #!/usr/bin/env bash
    
    sed -E 's/(w)(w*)/uL/g' "$1" > "$2"
    

    【讨论】:

    • (w)(w+) 在单个字符上会失败,不是吗?
    • @PaulHodges 确实...(w)(w*) 应该可以解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2021-02-21
    • 1970-01-01
    • 2012-06-08
    • 2019-09-02
    相关资源
    最近更新 更多