Home > OS >  How to read text from a file line by line, capitalize the first letter of every word, then write to
How to read text from a file line by line, capitalize the first letter of every word, then write to

Time:10-04

I am looking to read a file with names. I am trying to make sure that every name is capitalized properly. An example of the desired outcome

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

When running the code:

./namefixer.bash names.txt fixedNames.txt

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

Any Help?

My current code looks like this:

#!/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

CodePudding user response:

You can use the camelstr function provided by rquery (https://github.com/fuyuncat/rquery/releases)

[ 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

CodePudding user response:

You could do this with GNU sed:

sed -E 's/(\w)(\w*)/\u\1\L\2/g' names.txt > fixedNames.txt

This captures a "word" character (\w) in the first capture group, and then as many "word" characters as possible in the second capture group (\w*), and uses the special \u and \L sequences to control casing in the substitution string. The g flag applies the change globally for each line (instead of just for the first match).

If it really has to fit the exact command you show, you could make these the contents of namefixer.bash:

#!/usr/bin/env bash

sed -E 's/(\w)(\w*)/\u\1\L\2/g' "$1" > "$2"
  • Related