19

I'd like to add characters to the end of every line of text in a .txt document.

#Define Variables
$a = c:\foobar.txt
$b = get-content $a

#Define Functions
function append-text  
    {  
    foreach-Object  
        {  
        add "*"  
        }  
    }  

#Process Code
$b | append-text

Something like that. Essentially, load a given text file, add a "*" the the end of every single line of text in that text file, save and close.

4 Answers 4

30

No function necessary. This would do it:

$b|foreach {$_ +  "*"}
Sign up to request clarification or add additional context in comments.

2 Comments

And if you're wrists are bothering you gc c:\foobar.txt | %{"$_*"}. That is using aliases heavily but I tend to use PowerShell for a lot of one-offs at the command line and the less I have to type the more my wrists don't hate me. :-)
This definitely works, but I was hoping to keep it in function format so that I could call it again if necessary. You're probably right though, my goal on this script probably makes the need for a function unnecessary.
5
PS> (gc c:\foobar.txt) -replace '\S+$','$&*'

Comments

4

Soemthing like this should work:

function append-text { 
  process{
   foreach-object {$_ + "*"}
    } 
  }

6 Comments

If you use a filter, you don't need the process block at all e.g. filter Append-Text {"$_*"}
This works great! Is it possible add a redundancy check into this? Something that would check for the presence of "*", and if it is not at the end of a line, then add it?
Sure, filter Append-Text {if ($_ -match '\*\s*$') {$_} else {"$_*"}}
Sometimes people are just looking for an example of how to do something, and present a simple example to use that's easier to solve by some other method but giving them that doesn't really answer the question they were asking. Other times the giving them the alternate method is the "right" answer. Sometimes I guess wrong.
I think Keith's regex above '\s*$' is not correct. In any case instead of -match I would use -like, i.e. "$_ -notlike '*`'
|
0

Simply took about 2 hours to work it out, had never used Powershell before, but here you go:

cls
#Define Functions
(gc g:\foobar.txt) -replace '\S+$','$& 1GB RAM 1x 1 GB Stick' | out-file "g:\ram 6400s.txt"

Change the file location. First file is the file you want to edit. The secound one is the output file.

1 Comment

I don't understand, why "\S" (non-whitespace)? I'd think ".+" would be the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.