简体   繁体   English

Awk只能打印整行; 无法访问特定字段

[英]Awk can only print the whole line; cannot access the specific fields

I am currently working on my capstone project for Unix OS I. I'm very close to finishing, but I'm stuck on this part: basically, my assignment is to create a menu-based application wherein a user can enter a first and last name, I take that data, use it create a user name, and then I translate it from lowercase to uppercase, and finally store the data as: firstname:lastname:username . 我目前正在从事Unix OS I的顶峰项目。我非常接近完成,但是我坚持这一部分:基本上,我的任务是创建一个基于菜单的应用程序,用户可以在其中输入第一个姓,我使用该数据,使用它创建一个用户名,然后将其从小写转换为大写,最后将数据存储为: firstname:lastname:username

When asked to display the data I must display it based on the username instead of the first name, and formatted with spaces instead of tabs. 当要求显示数据时,我必须根据用户名而不是名字显示数据,并用空格而不是制表符格式化。 For example, it should look like: username firstname lastname . 例如,它应类似于: username firstname lastname So, I've tried multiple commands, such as sort and awk, but I seem to be only able to access the fields in the file as one big field; 因此,我尝试了多种命令,例如sort和awk,但是我似乎只能将文件中的字段作为一个大字段来访问。 eg when I do awk '{print NF}' users.txt to find the number of fields per row, it will return 1, clearly showing that my data is only being entered as one field, instead of the necessary 3 I need. 例如,当我awk '{print NF}' users.txt以查找每行的字段数时,它将返回1,清楚地表明我的数据仅作为一个字段输入,而不是我需要的3。 So my question is this: how do I go about changing the number of fields in the text file? 所以我的问题是:如何更改文本文件中的字段数? Here is my code to add the firstname:lastname:username to the file users.txt: 这是我的代码,用于将firstname:lastname:username添加到文件users.txt中:

userInfo=~/capstoneProject/users.txt
#make sure strings is not empty before writing to disk
if [[ "$fname" != ""  &&  "$lname" != "" ]]
then    #write to userInfo (users.txt)
echo "$fname:$lname:$uname" | tr a-z A-Z >> $userInfo
#change to uppercase using |
fi

Is it because of the way I am entering the data into my file? 是因为我将数据输入文件中的方式? Using echo "$fname:$lname:$uname" ? 使用echo "$fname:$lname:$uname"吗? Because this is the way my textbook showed me how to do it, and they had no trouble later on when using the sort function with specific fields, as I am trying to do now. 因为这是我的教科书向我展示如何做到的方式,并且以后在对特定字段使用sort函数时,他们也没有遇到任何麻烦,就像我现在正在尝试的那样。 If more detail is necessary, please let me know; 如果需要更多详细信息,请告诉我; this is the last thing I need before I can submit my project, due tonight. 这是我今晚提交项目之前需要做的最后一件事。

您的输入文件具有:分隔的字段,因此您需要告诉awk:

awk -F':' '{print NF}' users.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM