如何在文件的每一行开头添加字符串? [英] How can I prepend a string to the beginning of each line in a file?

查看:364
本文介绍了如何在文件的每一行开头添加字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下bash代码,它们逐行循环遍历文本文件.. im试图为每行添加工作前缀'prefix',但是却出现此错误:

I have the following bash code which loops through a text file, line by line .. im trying to prefix the work 'prefix' to each line but instead am getting this error:

rob@laptop:~/Desktop$ ./appendToFile.sh stusers.txt kp
stusers.txt
kp
./appendToFile.sh: line 11: /bin/sed: Argument list too long
115000_210org@house.com,passw0rd

这是bash脚本..

This is the bash script ..

#!/bin/bash

file=$1
string=$2

echo "$file"
echo "$string"

for line in `cat $file`
do
    sed -e 's/^/prefix/' $line
    echo "$line"
done < $file

我在这里做错什么了?

更新: 正面执行将所有行都转储到终端的一行中,可能与此相关吗?

Update: Performing head on file dumps all the lines onto a single line of the terminal, probably related?

rob@laptop:~/Desktop$ head stusers.txt
rob@laptop:~/Desktop$ ouse.com,passw0rd

推荐答案

单行awk命令也可以解决问题:

a one-line awk command should do the trick also:

awk '{print "prefix" $0}' file

这篇关于如何在文件的每一行开头添加字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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