简体   繁体   English

如何使用Shell从文件中的一行复制值并将其粘贴到新文件中?

[英]How to copy value from a line in a file and paste it into a new file using Shell?

I have a file containing my personal details (.txt). 我有一个包含我的个人详细信息(.txt)的文件。 How can I, via a shell script, copy only a few lines in the file and bring it to a new .txt file?. 我如何通过Shell脚本仅复制文件中的几行并将其带到新的.txt文件中?

Name: Nik
Date of Birth: 5.06.92
Address: 1234 Main St.
SSN: 123-45-6789

I would like to copy my address 1234 Main St. to another file. 我想将我的地址1234 Main St.复制到另一个文件。

怎么样:

awk -F': ' '/^Address/{print $2}' personalinfo.txt | tee newfile.txt

If you want to copy a specific line by its number : 如果要按编号复制特定行:

sed -n '1 p' personal_details.txt > newfile.txt # Where 1 is the line number

If you want to copy a line by its contents : 如果要按行内容复制行:

grep 'Name' personal_details.txt > newfile.txt

If you want to copy a line but only its value, not the name of the field: 如果要复制一行,而只复制其值,而不是字段名:

awk -F':' '/^Name/ {print $2}'  personal_details.txt > newfile.txt

Regards! 问候!

Just in case you would like to use only grep or pcregrep (in case you are on a macOS): 万一您只想使用greppcregrep (如果您使用的是macOS):

grep -oP "Address: \K.+" file.txt > newfile.txt

Or in macOS: 或在macOS中:

pcregrep -o "Address: \K.+" file.txt > newfile.txt

The \\K can be read as exclude everything at the left before it and return only the right part .+ \\K可以理解为排除在它之前左边的所有内容,而只返回右边的部分.+

暂无
暂无

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

相关问题 使用终端(或Shell)将文件的一部分复制/粘贴到另一个文件中 - Copy/Paste part of a file into another file using Terminal (or Shell) 如何将文本从一个 Vim 文件复制/粘贴到另一个 shell 选项卡中的另一个 Vim 文件? - How can I copy/paste text from one Vim file to another Vim file in another shell tab? Shell脚本从目录复制并粘贴随机文件 - Shell Script copy and paste a random file from a directory Bash / ZSH - 如何从特定行复制到文件末尾,然后粘贴到另一个文件的第 1 行,同时保留该文件中的所有文本 - Bash / ZSH - How to copy from a specific line to the end of a file, then paste at line 1 of another file whist preserving all text in that file 从几个文件中复制字符串并将其粘贴到 bash 中的新文件中 - copy strings from a few files and paste it into a new file in bash 使用 shell 脚本将特定单词从一个文件复制到另一个文件 - Copy specific word from a file to another file using shell script bash-检查特定列中的单词,检查该行其他列中的值,将其剪切并粘贴到新的文本文件中 - bash - check for word in specific column, check value in other column of this line, cut and paste the line to new text file 如何在 shell 文件中使用粘贴命令 - How to use paste command in the shell file 如何使用 shell 脚本从文本文件中获取选定的值 - how to fetch a selected value from a text file using a shell script 使用Shell脚本从文件读取值 - Read value from file using a shell script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM