故障排除bash脚本能够利用在每个单词的第一个字母 [英] Troubleshooting bash script to capitalize first letter in every word

查看:169
本文介绍了故障排除bash脚本能够利用在每个单词的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的文本文件:

I have a text file in the following format:

jAY
JAY
JaY

eVAns
Evans
Evans

我试图做的是将所有的都为小写再大写每个单词的第一个字母。对于我的剧本,但我不打印出正确的信息。

What I'm trying to do is convert everything to lowercase and then capitalize the first letter of every word. For my script, however, I'm not printing out the correct information.

#!/bin/bash

FILE=names.txt

echo "#################################"
k=1
while read line;do

VAR=$line
VARCAP=$( echo "${VAR}" | tr '[A-Z]' '[a-z]')";
VARCAP1=$( echo "${VARCAP}" | awk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1')

echo "Line # $k: $VARCAP1"
((k++))
done < $FILE
echo "Total number of lines in file: $k"

一切工作,直到我加入的所有字母转换为小写行 - 所以这是在我的问题所在。这是我曾经写过的第一个bash脚本,所以说我是绿色轻描淡写。

Everything was working until I added the line to convert all the letters to lowercase - so that is where my problem lies. This is the first bash script I've ever written, so to say I'm green is an understatement.

任何援助将AP preciated。

Any assistance would be appreciated.

推荐答案

正如我在OP的​​评论说,你可以使用(在Bash≥4)以下内容:

As I said in a comment of the OP, you can use (in Bash≥4) the following:

${var,,}
${var^}

分别有小写的VAR 的扩大和 VAR 与第一个字母大写小写。好消息是,这也适用于一个阵列中的每个字段。

to respectively have the expansion of var in lowercase and var in lowercase with first letter capitalize. The good news is that this also works on each field of an array.

注意:的从你的问题,你是否需要在每个应用此的一行字的,或在每个目前尚不清楚行的。下面地址的行的各字的问题。详情请参阅史蒂芬竹篙答案,仅处理每一行。

Note. It is not clear from you question whether you need to apply this on each word of a line, or on each line. The following addresses the problem of each word of a line. Please refer to Steven Penny's answer to process only each line.

在这里你去,在一个更​​好的风格!

Here you go, in a much better style!

#!/bin/bash

file=names.txt
echo "#################################"
k=1
while read -r -a line_ary;do
    lc_ary=( "${line_ary[@],,}" )
    echo "Line # $k: ${lc_ary[@]^}"
    ((++k))
done < "$file"
echo "Total number of lines in file: $k"

首先我们先读每一行作为数组 line_ary (每个字段是一个字)。

First we read each line as an array line_ary (each field is a word).

部分 lc_ary =($ {line_ary [@] ,,})转换的各个领域 line_ary 全部小写和结果数组存储到 lc_ary

The part lc_ary=( "${line_ary[@],,}" ) converts each field of line_ary to all lowercase and stores the resulting array into lc_ary.

我们现在只需要适用 ^ 来数组 lc_ary 和回声它。

We now only need to apply ^ to the array lc_ary and echo it.

这篇关于故障排除bash脚本能够利用在每个单词的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆