0

i would like to add a simply word in a existing file on a specific line. I already try with sed or awk or echo, cat and so on, but without expect result.

I tried with several command:

!/bin/bash

read nome

awk "BEGIN {print "$nome"}" > file.txt

File example:

word1 word2 word3 word4
word1 word2 word3 word4 word5

And i want the result:

word1 word2 word3 word4
word1 word2 word3 word4 word5 word6
  • In python, read the contents of the file using `readlines()`, giving you a list containing each line of the original file. Append your word to the line of your choice, then write all lines (including the modified one) back to a file, either the original one, or a new one. – Danielle M. Nov 22 '22 at 16:58
  • 1
    If the final line isn't newline terminated, this is easy (change `>`, which means "write to emptied file", to `>>`, meaning "append"). If it's newline terminated, it's tougher. Which is it? – ShadowRanger Nov 22 '22 at 16:59
  • What do you mean by "specific line"? is it by line number? – Hellmar Becker Nov 22 '22 at 16:59
  • 1
    OP please clarify if you always mean the last line of the file or not. answers will differ. If you don't mean the last line I will vote to reopen the question – Ryan Haining Nov 22 '22 at 17:01
  • @RyanHaining: If they want to modify a single line not at the end of the file, it's still just one more duplicate of [Editing specific line in text file in Python](https://stackoverflow.com/q/4719438/364696), or for `bash` usage (where I'm pretty sure you can assume `sed` exists), [Using sed to retrieve and modify a single line in the file](https://stackoverflow.com/q/23957082/364696), or for changing the first line of a file [change first line of a file using bash](https://stackoverflow.com/q/31240753/364696). The question is definitely a duplicate. – ShadowRanger Nov 22 '22 at 20:54
  • yes @HellmarBecker i mean line number – Michele Cozzolino Nov 23 '22 at 08:53
  • @RyanHaining yes, i meant the last line, as i wrote in my sample i wrote just 2 line, it's implied – Michele Cozzolino Nov 23 '22 at 08:58
  • My goal it's add, (not append), a word after the last word in the file separeted by space, i wrote "in a specific line" because i don't know if all program language support this choice – Michele Cozzolino Nov 23 '22 at 09:02
  • @MicheleCozzolino "on a specific line" implies you would want to be able to specify a line number. Your example uses the last line, which is easier. Can you distinguish "add" from "append"? What would add do that append wouldn't? – Ryan Haining Nov 23 '22 at 20:17

0 Answers0